<template>
  <a-config-provider :locale="locale">
    <router-view />
  </a-config-provider>
</template>

<script lang="ts" setup>
  import { computed, onMounted } from 'vue';
  import enUS from '@arco-design/web-vue/es/locale/lang/en-us';
  import zhCN from '@arco-design/web-vue/es/locale/lang/zh-cn';
  import useLocale from '@/hooks/locale';
  import GoEasy from 'goeasy-lite';
  import { CaddieScoreConfirmMessage } from '@/types/message';
  import { AnyObject } from '@/types/global';

  const { currentLocale } = useLocale();
  const locale = computed(() => {
    switch (currentLocale.value) {
      case 'zh-CN':
        return zhCN;
      case 'en-US':
        return enUS;
      default:
        return zhCN;
    }
  });

  function sendNotification(message: CaddieScoreConfirmMessage) {
    const notification = new Notification('提醒', {
      body: `球童提交了${message.nickname}的成绩`,
      icon: 'https://admin.qmx-golf.com/favicon.png',
    });
  }

  onMounted(() => {
    const goeasy = GoEasy.getInstance({
      host: 'hangzhou.goeasy.io',
      appkey: 'BS-f7c63a77098f421d931e7f5d0a9a4686',
      modules: ['pubsub'],
    });

    // @ts-ignore
    goeasy.connect({
      onSuccess() {
        console.log('success connected');
      },
    });

    // @ts-ignore
    goeasy.pubsub.subscribe({
      channel: 'caddie_score_confirm',
      onMessage(message: AnyObject) {
        const messageContent = message.content as string;
        const messageInfo = JSON.parse(
          messageContent
        ) as CaddieScoreConfirmMessage;
        if (Notification.permission === 'granted') {
          sendNotification(messageInfo);
        } else {
          Notification.requestPermission().then((permission) => {
            if (permission === 'granted') {
              sendNotification(messageInfo);
            }
          });
        }
      },
    });
  });
</script>
